package cn.edu.kzjsxy.graduationproject.common;

import cn.edu.kzjsxy.graduationproject.entity.Users;
import cn.edu.kzjsxy.graduationproject.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author：chén jiā jùn
 * @Create：2024年04月03日18:47
 * 解析token令牌和用户信息的！
 */
@Component
public class TokenUtil {
	//	用户的信息的service
	@Autowired
	private IUsersService userService;
	// redis的service
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	//  token有效期
	@Value("${spring.redis.cache.redis.time-to-live}")
	private Long timeToLive;

	//  token有效期
	@Value("${spring.redis.cache.redis.update-time}")
	private Long updateTime;




//  解析token
public Users resolveToken (HttpServletRequest request) {
	String token = request.getHeader(ResultCode.TOKEN);
	if (token == null || token.isEmpty()) {
		throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "登录已过期");
	}
	// 尝试从缓存中获取 userId
	String userId = redisTemplate.opsForValue().get(token);
	if (userId != null) {
		// 获取 token 的剩余过期时间（秒）
		Long ttl = redisTemplate.getExpire(token, TimeUnit.SECONDS);
		// 如果 ttl 存在且小于 updateTime，则更新 token 到期时间
		if (ttl != null && ttl < updateTime) {
			redisTemplate.expire(token, timeToLive, TimeUnit.SECONDS);
		}
		// 根据 userId 获取 Users 对象
		Users users = userService.getById(userId);
		if (users != null) {
			return users;
		} else {
			// userId 对应的用户不存在，抛出异常
			throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "登录已过期");
		}
	} else {
		throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "登录已过期");
	}
}


}
